package com.bsoft.gol.hcs.specialist.dao;

/**
 * @Author:FangZhiyi
 * @Description
 * @Data Created in 2020/7/15 9:49
 * @Moddified By:
 */

import ctd.persistence.annotation.DAOMethod;
import ctd.persistence.annotation.DAOParam;
import ctd.persistence.support.hibernate.template.AbstractHibernateStatelessResultAction;
import ctd.persistence.support.hibernate.template.HibernateSessionTemplate;
import ctd.persistence.support.hibernate.template.HibernateStatelessResultAction;
import ctd.util.converter.ConversionUtils;
import org.apache.commons.lang3.StringUtils;
import org.atag.dao.action.QoHibernateStatelessResultAction;
import org.atag.dao.ext.HibernateExtendDAO;
import org.atag.dao.model.SimplePageInfo;
import org.hibernate.Query;
import org.hibernate.SQLQuery;
import org.hibernate.StatelessSession;
import org.hibernate.criterion.CriteriaSpecification;
import com.bsoft.gol.hcs.specialist.bean.qo.FollowUpRouteQo;
import com.bsoft.gol.hcs.specialist.bean.qo.QueryAfterHosRecordQo;
import com.bsoft.gol.hcs.specialist.bean.request.DocIdQo;
import com.bsoft.gol.hcs.specialist.bean.request.QueryFollowUpRouteReq;
import com.bsoft.gol.hcs.specialist.bean.response.FusAfterHosRecordDTO;
import com.bsoft.gol.hcs.specialist.bean.vo.FollowUpCountVo;
import com.bsoft.gol.hcs.specialist.bean.vo.FollowUpRecordsVO;
import com.bsoft.gol.hcs.specialist.bean.vo.FollowUpRouteVO;
import com.bsoft.gol.hcs.specialist.entity.FollowUpRoute;
import com.bsoft.gol.hcs.utils.CommonUtils;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public abstract class FollowUpRouteDAO extends HibernateExtendDAO<FollowUpRoute> {

    @DAOMethod(sql = " from  FollowUpRoute where medical_team_id =:teamId ")
    public abstract List<FollowUpRoute> queryDocTeamDiseaseList(@DAOParam("teamId") Long teamId);

    @DAOMethod(sql = " from FollowUpRoute where organization_id =:orgId and FIND_IN_SET(:deptId, department_id)>0 and" +
            " followType=:followType ")
    public abstract List<FollowUpRoute> findFusList(@DAOParam("orgId") String orgId,
                                                    @DAOParam("deptId") String deptId,
                                                    @DAOParam("followType") String followType);

    /**
     * @param diseaseTypeId
     * @throws
     * @description: 根据病种查询随访路径（随访路径有多版本的情况，也只有启用状态的版本可用）
     * @return: java.util.List<specialist.entity.FollowUpRoute>
     * @author: tongtp
     * @date: 2020/7/21 15:06
     */
    @DAOMethod(sql = " from FollowUpRoute where diseaseTypeId =:diseaseTypeId AND status = 1 ")
    public abstract List<FollowUpRoute> queryByDiseaseTypeId(@DAOParam("diseaseTypeId") Long diseaseTypeId);

    /**
     * 根据idList 和就诊类型获取路径列表
     */
    @DAOMethod(sql = " from FollowUpRoute where routeId in (:routeIdList) AND status = 1 ")
    public abstract List<FollowUpRoute> queryByIds(@DAOParam("routeIdList") List<Long> routeIdList);

    /**
     * @param status
     * @throws
     * @description: 根据随访大类和启用状态查询随访路径
     * @return: java.util.List<specialist.entity.FollowUpRoute>
     * @author: tongtp
     * @date: 2020/7/21 15:06
     */
    @DAOMethod(sql = " from FollowUpRoute where followType = :followType and status = :status ")
    public abstract List<FollowUpRoute> queryByFollowTypeAndStatus(@DAOParam("followType") String followType, @DAOParam(
            "status") Byte status);

    @DAOMethod(sql = "update FollowUpRoute set status=:status where routeId=:routeId")
    public abstract void updateEnableOrDisableRoute(@DAOParam("routeId") Long routeId, @DAOParam("status") Byte status);



    public List<FollowUpRoute> queryFollowUpRouteListByOrdOrDept(final String orgId, final String deptId, final String followType) {
        HibernateStatelessResultAction<List<FollowUpRoute>> action =
                new AbstractHibernateStatelessResultAction<List<FollowUpRoute>>() {
                    @Override
                    public void execute(StatelessSession ss) {
                        StringBuffer stringBuffer = new StringBuffer();
                        stringBuffer.append("SELECT route_id routeId, route_name routeName, organization_id organizationId, follow_type followType, " +
                                "organization_name organizationName, parent_route_id parentRouteId, disease_type_id diseaseTypeId, " +
                                "disease_type_name diseaseTypeName, department_id departmentId, department_name " +
                                "departmentName,visit_type visitType,check_plan checkPlan, create_dept_id createDeptId,create_dept_name createDeptName, status, version_number versionNumber, creator_id creatorId, creator_name " +
                                "creatorName, creator_dt createDt, modify_id modifyId, modify_username modifyUsername,modify_dt modifyDt FROM follow_up_route  WHERE status != 9  ");
                        if (CommonUtils.isNotEmpty(orgId)) {
                            stringBuffer.append(" and organization_id=:orgId");
                        }
                        if (StringUtils.isNotEmpty(deptId)) {
                            stringBuffer.append(" and create_dept_id=:deptId");
                        }
                        if (CommonUtils.isNotEmpty(followType)) {
                            stringBuffer.append(" and follow_type=:followType");
                        }
                        stringBuffer.append(" order by modify_dt desc ");
                        Query sqlQuery = ss.createSQLQuery(stringBuffer.toString());
                        if (CommonUtils.isNotEmpty(orgId)) {
                            sqlQuery.setParameter("orgId", orgId);
                        }
                        if (StringUtils.isNotEmpty(deptId)) {//创建科室ID
                            sqlQuery.setParameter("deptId", deptId);
                        }
                        if (CommonUtils.isNotEmpty(followType)) {//随访类型
                            sqlQuery.setParameter("followType", followType);
                        }
                        sqlQuery.setResultTransformer(CriteriaSpecification.ALIAS_TO_ENTITY_MAP);
                        List<Map> dbList = sqlQuery.list();
                        setResult(mapToList(dbList));
                    }
                };
        HibernateSessionTemplate.instance().execute(action);
        return action.getResult();
    }


    public List<FollowUpRoute> queryFollowUpRouteList(final QueryFollowUpRouteReq queryFollowUpRouteReq) {
        HibernateStatelessResultAction<List<FollowUpRoute>> action =
                new AbstractHibernateStatelessResultAction<List<FollowUpRoute>>() {
                    @Override
                    public void execute(StatelessSession ss) {
                        StringBuffer stringBuffer = getFollowUpRouteListStringBuffer(queryFollowUpRouteReq);
                        Query sqlQuery = getQuery(ss, queryFollowUpRouteReq, stringBuffer);
                        int first = queryFollowUpRouteReq.getPageNo() > 0 ?
                                (queryFollowUpRouteReq.getPageNo() - 1) * queryFollowUpRouteReq.getPageSize() : 0;
                        sqlQuery.setFirstResult(first);
                        sqlQuery.setMaxResults(queryFollowUpRouteReq.getPageSize());
                        sqlQuery.setResultTransformer(CriteriaSpecification.ALIAS_TO_ENTITY_MAP);
                        List<Map> dbList = sqlQuery.list();
                        setResult(mapToList(dbList));
                    }
                };
        HibernateSessionTemplate.instance().execute(action);
        return action.getResult();
    }

    public int queryFollowUpRouteCount(final QueryFollowUpRouteReq queryFollowUpRouteReq) {
        HibernateStatelessResultAction<Integer> action = new AbstractHibernateStatelessResultAction<Integer>() {
            @Override
            public void execute(StatelessSession ss) {
                StringBuffer stringBuffer = getFollowUpRouteCountStringBuffer(queryFollowUpRouteReq);
                Query sqlQuery = getQuery(ss, queryFollowUpRouteReq, stringBuffer);
                sqlQuery.setResultTransformer(CriteriaSpecification.ALIAS_TO_ENTITY_MAP);
                List<Map> dbList = sqlQuery.list();
                if (CommonUtils.isNotEmpty(dbList)) {
                    setResult(Integer.valueOf(String.valueOf(dbList.get(0).get("countValue"))));
                } else {
                    setResult(0);
                }
            }
        };
        HibernateSessionTemplate.instance().execute(action);
        return action.getResult();
    }

    private Query getQuery(StatelessSession ss, QueryFollowUpRouteReq queryFollowUpRouteReq,
                           StringBuffer stringBuffer) {
        Query sqlQuery = ss.createSQLQuery(stringBuffer.toString());
        sqlQuery.setParameter("orgId", queryFollowUpRouteReq.getOrganizationId());
        if (queryFollowUpRouteReq.getDiseaseTypeId() != null) {//慢病ID
            sqlQuery.setParameter("diseaseTypeId", queryFollowUpRouteReq.getDiseaseTypeId());
        }
        if (StringUtils.isNotEmpty(queryFollowUpRouteReq.getCreateDeptId())) {//创建科室ID
            sqlQuery.setParameter("createDeptId", queryFollowUpRouteReq.getCreateDeptId());
        }
        if (CommonUtils.isNotEmpty(queryFollowUpRouteReq.getFollowType())) {//随访类型
            sqlQuery.setParameter("followType", queryFollowUpRouteReq.getFollowType());
        }
        if (StringUtils.isNotEmpty(queryFollowUpRouteReq.getStatus())) {//路径状态
            sqlQuery.setParameter("status", queryFollowUpRouteReq.getStatus());
        }
        return sqlQuery;
    }

    private StringBuffer getFollowUpRouteListStringBuffer(QueryFollowUpRouteReq queryFollowUpRouteReq) {
        StringBuffer stringBuffer = new StringBuffer();
        stringBuffer.append("SELECT route_id routeId, route_name routeName, organization_id organizationId, follow_type followType, " +
                "organization_name organizationName, parent_route_id parentRouteId, disease_type_id diseaseTypeId, " +
                "disease_type_name diseaseTypeName, department_id departmentId, department_name " +
                "departmentName,visit_type visitType,check_plan checkPlan, create_dept_id createDeptId,create_dept_name createDeptName, status, version_number versionNumber, creator_id creatorId, creator_name " +
                "creatorName,  modify_id modifyId, modify_username modifyUsername,modify_dt modifyDt,creator_dt creatorDt ");
        return getFollowUpRouteStringBuffer(stringBuffer, queryFollowUpRouteReq);
    }

    private StringBuffer getFollowUpRouteCountStringBuffer(QueryFollowUpRouteReq queryFollowUpRouteReq) {
        StringBuffer stringBuffer = new StringBuffer();
        stringBuffer.append("SELECT count(1 ) countValue");
        return getFollowUpRouteStringBuffer(stringBuffer, queryFollowUpRouteReq);
    }

    private StringBuffer getFollowUpRouteStringBuffer(StringBuffer stringBuffer,
                                                      QueryFollowUpRouteReq queryFollowUpRouteReq) {
        stringBuffer.append(" FROM follow_up_route  WHERE status != 9 and organization_id=:orgId ");
        if (queryFollowUpRouteReq.getDiseaseTypeId() != null) {
            stringBuffer.append(" and disease_type_id=:diseaseTypeId");
        }
        if (StringUtils.isNotEmpty(queryFollowUpRouteReq.getStatus())) {
            stringBuffer.append(" and status=:status");
        }
        if (StringUtils.isNotEmpty(queryFollowUpRouteReq.getCreateDeptId())) {
            stringBuffer.append(" and create_dept_id=:createDeptId");
        }
        if (StringUtils.isNotEmpty(queryFollowUpRouteReq.getApplyDepartmentId())) {
            stringBuffer.append(" and department_id like '%" + queryFollowUpRouteReq.getApplyDepartmentId() + "%' ");
        }
        if (CommonUtils.isNotEmpty(queryFollowUpRouteReq.getFollowType())) {
            stringBuffer.append(" and follow_type=:followType");
        }
        if (StringUtils.isNotEmpty(queryFollowUpRouteReq.getKeyWords())) {
            stringBuffer.append(" and route_name like '%" + queryFollowUpRouteReq.getKeyWords() + "%' ");
        }
        stringBuffer.append(" order by creator_dt desc ");
        return stringBuffer;
    }


    private List<FollowUpRoute> mapToList(List<Map> maps) {
        List<FollowUpRoute> docTeamListRespList = new ArrayList<>();
        for (Map map : maps) {
            docTeamListRespList.add(ConversionUtils.convert(map, FollowUpRoute.class));
        }
        return docTeamListRespList;
    }


    public SimplePageInfo<FusAfterHosRecordDTO> getAfterHosRecord(QueryAfterHosRecordQo qo) {
        QoHibernateStatelessResultAction<FusAfterHosRecordDTO, QueryAfterHosRecordQo> action = new QoHibernateStatelessResultAction<>(true, qo, FusAfterHosRecordDTO.class);
        String sql = "SELECT " +
                " {{" +
                "a.record_id AS recordId,a.tenant_id AS tenantId,a.organization_id AS organizationId,a.organization_name AS organizationName," +
                "a.route_detail_type AS routeDetailType,a.department_id AS departmentId,a.department_name AS departmentName,a.doctor_id AS doctorId," +
                "a.doc_id AS docId,a.doctor_name AS doctorName,a.patient_id AS patientId,a.card_type AS cardType,a.card_number AS cardNumber," +
                "a.patient_name AS patientName,a.patient_sex AS patientSex,a.patient_age AS patientAge,a.telephone AS telephone,a.address AS address," +
                "a.plan_time AS planTime,a.result_code AS resultCode,a.result_code_detail AS resultCodeDetail,a.follow_up_status AS followUpStatus," +
                "a.create_id AS createId,a.create_time AS createTime,a.execute_id AS executeId,a.execute_name AS executeName,a.execute_time AS executeTime," +
                "a.stop_id AS stopId,a.stop_time AS stopTime,a.lock_id AS lockId,a.lock_name AS lockName,a.lock_time AS lockTime,a.lock_flag AS lockFlag," +
                "a.route_id AS routeId,a.route_name AS routeName,a.route_detail_id AS routeDetailId,a.read_flag AS readFlag,a.notify_flag AS notifyFlag," +
                "a.plan_notify_date AS planNotifyDate,a.notify_status AS notifyStatus,a.medical_record_id AS medicalRecordId,a.medical_record_name AS medicalRecordName," +
                "a.patient_medical_card_number AS patientMedicalCardNumber,a.patient_medical_card_type AS patientMedicalCardType,a.modify_dt AS modifyDt," +
                "a.patient_type AS patientType,a.outpatient_number AS outpatientNumber,a.inpatient_number AS inpatientNumber,a.cancel_id AS cancelId,a.cancel_name AS cancelName," +
                "a.cancel_time AS cancelTime," +
                " a.audit_status AS auditStatus, " +
                " a.audit_id AS auditId, " +
                " a.audit_name AS auditName, " +
                " a.audit_time AS auditTime, " +
                " a.visit_time AS visitTime, " +
                " a.visit_no AS visitNo, " +
                " a.cancel_reason AS cancelReason }}" +
                "  FROM  " +
                " fus_after_hos_record a " +
                "  WHERE 1=1 " +
                "  and a.audit_status !=0 ";

        action.setSql(sql);
        action.addCondition(" and a.department_id in(:deptIdList)   ");
        action.addCondition(" and a.organization_id = :organizationId ");
        //就诊时间
        if ("1".equals(qo.getTimeType())) {
            action.addCondition(" AND a.visit_time >= :planStartTime ");
            action.addCondition(" AND a.visit_time <= :planEndTime ");
            //随访时间
        } else if ("2".equals(qo.getTimeType())) {
            action.addCondition(" AND a.plan_time >= :planStartTime ");
            action.addCondition(" AND a.plan_time <= :planEndTime ");
        }
        action.addCondition(" and a.route_id  =:routeId   ");
        action.addCondition(" and a.route_id  in(:routeIdList)   ");

        action.addCondition(" and a.audit_status  =:auditStatus   ");
        String keyWord = qo.getKeyWord();
        if (!StringUtils.isEmpty(keyWord)) {
            qo.setKeyWord(qo.getKeyWord() + "%");
            action.addCondition("and (a.patient_medical_card_number like:keyWord or a.patient_name like:keyWord)");
        }
        HibernateSessionTemplate.instance().execute(action);
        return action.getSimpleResultPage();

    }

    private boolean isNumber(String number) {
        if (org.springframework.util.StringUtils.isEmpty(number)) {
            return false;
        }
        Pattern p = Pattern.compile("[0-9]+");
        Matcher m = p.matcher(number);
        return m.find();
    }

    public SimplePageInfo<FollowUpRecordsVO> getFollowUpRecords(DocIdQo qo) {
        QoHibernateStatelessResultAction<FollowUpRecordsVO, DocIdQo> action = new QoHibernateStatelessResultAction<>(true, qo, FollowUpRecordsVO.class);
        String sql = "SELECT " +
                " {{" +
                " a.record_id AS recordId, " +
                " a.organization_id AS organizationId, " +
                " a.route_detail_type AS routeDetailType, " +
                " a.disease_type_id AS diseaseTypeId, " +
                " a.disease_type_name AS diseaseTypeName, " +
                " a.department_id AS departmentId, " +
                " a.department_name AS departmentName, " +
                " a.doctor_id AS doctorId, " +
                " a.doc_id AS docId, " +
                " a.doctor_name AS doctorName, " +
                " a.patient_id AS patientId, " +
                " a.card_type AS cardType, " +
                " a.card_number AS cardNumber, " +
                " a.patient_name AS patientName, " +
                " a.patient_sex AS patientSex, " +
                " a.patient_age AS patientAge, " +
                " a.telephone AS telephone, " +
                " a.address AS address, " +
                " a.plan_time AS planTime, " +
                " a.result_code AS resultCode, " +
                " a.follow_up_status AS followUpStatus, " +
                " a.create_id AS createId, " +
                " a.create_time AS createTime, " +
                " a.execute_id AS executeId, " +
                " a.execute_name AS executeName, " +
                " a.execute_time AS executeTime, " +
                " a.stop_id AS stopId, " +
                " a.stop_time AS stopTime, " +
                " a.route_id AS routeId, " +
                " a.route_name AS routeName, " +
                " a.route_detail_id AS routeDetailId, " +
                " a.user_info_id AS userInfoId, " +
                " a.is_read AS isRead, " +
                " a.is_notify AS isNotify, " +
                " a.plan_notify_date AS planNotifyDate, " +
                " a.notify_status AS notifyStatus, " +
                " a.medical_record_id AS medicalRecordId, " +
                " a.medical_record_name AS medicalRecordName, " +
                " a.patient_medical_card_number AS patientMedicalCardNumber, " +
                " a.patient_medical_card_type AS patientMedicalCardType, " +
                " a.team_chronic_group_id AS teamChronicGroupId, " +
                " a.medical_team_id AS medicalTeamId, " +
                " a.medical_team_name AS medicalTeamName, " +
                " a.answer_abnormal AS answerAbnormal, " +
                " a.abnormal_read_flag AS abnormalReadFlag, " +
                " a.medical_record_upload_flag AS medicalRecordUploadFlag, " +
                " a.gmt_create AS gmtCreate, " +
                " a.gmt_modified AS gmtModified, " +
                " a.auto_create_flag AS autoCreateFlag, " +
                " a.audit_status AS auditStatus, " +
                " a.audit_id AS auditId, " +
                " a.audit_name AS auditName, " +
                " a.audit_time AS auditTime, " +
                " d.apply_type AS applyType, " +
                " d.person_id AS personId, " +
                " d.org_id AS orgId, " +
                " a.audit_reason AS auditReason  }}" +
                "  FROM  " +
                " follow_up_records a , " +
                "  fus_team_chronic_group_record d  " +
                "  WHERE 1=1 " +
                " and " +
                "   a.team_chronic_group_id = d.team_chronic_group_id   " +
                "  and a.audit_status !=0 ";
        action.setSql(sql);
        if ("1".equals(qo.getApplyType())) {
            action.addCondition("  and d.apply_type =:applyType");
        } else if ("2".equals(qo.getApplyType())) {
            action.addCondition("  and d.apply_type =:applyType");
        } else if ("3".equals(qo.getApplyType())) {
            action.addCondition("  and d.apply_type =:applyType");
        }
        action.addCondition(" and a.disease_type_id =:diseaseTypeId ");
        action.addCondition(" and a.route_id  =:routeId   ");
        action.addCondition(" and a.route_id  in(:routeIdList)   ");
        action.addCondition(" and a.audit_status  =:auditStatus   ");
        String keyWord = qo.getKeyWord();
        if (!StringUtils.isEmpty(keyWord)) {
            if (isNumber(keyWord)) {
                //诊疗卡号码
                action.addCondition("and a.patient_medical_card_number =:keyWord");
            } else {
                //患者姓名
                action.addCondition("and a.patient_name =:keyWord ");
            }
        }
        HibernateSessionTemplate.instance().execute(action);
        return action.getSimpleResultPage();

    }


    public List<FollowUpCountVo> getRouteTreeList(DocIdQo qo) {

        QoHibernateStatelessResultAction<FollowUpCountVo, DocIdQo> action = new QoHibernateStatelessResultAction<>(false, qo, FollowUpCountVo.class);

        String sql = " SELECT " +
                "  b.route_id AS routeId, " +
                "  b.route_name AS routeName, " +
                " b.organization_id AS organizationId, " +
                " b.organization_name AS organizationName " +
                " FROM " +
                " doc_team_fus_authority b " +
                " WHERE " +
                " 1=1 ";

        action.setSql(sql);
        action.addCondition(" and b.medical_team_id in(:teamIdList)");
        action.addSql("GROUP BY b.route_id,b.route_name,b.organization_id,b.organization_name");
        HibernateSessionTemplate.instance().execute(action);
        return action.getResultList();
    }

    /**
     * 专病随访机构路径查询
     *
     * @param qo the qo
     * @author Qulc - 2022/6/6 19:56
     */
    public List<FollowUpCountVo> getDiseaseRouteTreeList(DocIdQo qo) {

        QoHibernateStatelessResultAction<FollowUpCountVo, DocIdQo> action = new QoHibernateStatelessResultAction<>(false, qo, FollowUpCountVo.class);

        String sql = " SELECT " +
                " b.route_id AS routeId, " +
                " b.route_name AS routeName, " +
                " b.organization_id AS organizationId, " +
                " b.organization_name AS organizationName  " +
                "FROM " +
                " follow_up_route b, " +
                " doc_team_disease c " +
                "WHERE " +
                " b.disease_type_id = c.chronic_disease_id  " +
                " AND b.check_plan = '1'  ";
        action.setSql(sql);
        action.addCondition(" and c.medical_team_id in(:teamIdList)");

        action.addSql("GROUP BY b.route_id,b.route_name,b.organization_id,b.organization_name");
        HibernateSessionTemplate.instance().execute(action);
        return action.getResultList();
    }

    /**
     * @description: 查询路径下的需要审核的随访计划数量
     * @author: chenJij@bsoft.com.cn
     * @date: 2022/6/7 20:25
     * @param: type 随访类型  1 院后随访   2 专病随访
     * @return: java.util.List<java.util.Map>
     */
    public Map queryPlanCount(final String type) {

        HibernateStatelessResultAction<Map> action = new AbstractHibernateStatelessResultAction<Map>() {
            @Override
            public void execute(StatelessSession ss) {
                StringBuffer stringBuffer = new StringBuffer();
                stringBuffer.append(" SELECT   route_id routeId,   count( route_id ) planCount  FROM ");
                if ("1".equals(type)) {
                    stringBuffer.append(" fus_after_hos_record ");
                } else {
                    stringBuffer.append(" follow_up_records ");
                }
                stringBuffer.append(" WHERE  audit_status != 0 AND route_id != 0 GROUP BY route_id ");

                SQLQuery sqlQuery = ss.createSQLQuery(stringBuffer.toString());
                sqlQuery.setResultTransformer(CriteriaSpecification.ALIAS_TO_ENTITY_MAP);
                List<Map> dbList = sqlQuery.list();
                Map planCountMap = new HashMap();
                if (CommonUtils.isNotEmpty(dbList)) {
                    for (Map map : dbList) {
                        Long routeId = Long.valueOf(String.valueOf(map.get("routeId")));
                        Integer planCount = Integer.valueOf(String.valueOf(map.get("planCount")));
                        planCountMap.put(routeId, planCount);
                    }
                }
                setResult(planCountMap);
            }
        };
        HibernateSessionTemplate.instance().execute(action);
        return action.getResult();
    }

    /**
     * @description: 查询路径下的需要审核的随访计划数量
     * @author: chenJij@bsoft.com.cn
     * @date: 2022/6/7 20:25
     * @param: type 随访类型  1 院后随访   2 专病随访 , final Long routeId
     * @return: java.util.List<java.util.Map>
     */
    public List<Long> queryRouteIdList(final String type, final String docId,final List<Long> teamIdList) {

        HibernateStatelessResultAction<List<Long>> action = new AbstractHibernateStatelessResultAction<List<Long>>() {
            @Override
            public void execute(StatelessSession ss) {
                StringBuffer stringBuffer = new StringBuffer();
                if ("1".equals(type)) {
                    stringBuffer.append(" SELECT " +
                            " DISTINCT b.route_id as routeId  " +
                            "FROM " +
                            " doc_team_fus_authority b " +
                            "WHERE " +
                            //"b.route_id =:routeId  " +
                            "  b.medical_team_id in(:teamIdList) ");

                } else {
                    stringBuffer.append(" SELECT " +
                            " DISTINCT c.route_id as routeId  " +
                            "FROM " +
                            " doc_team_disease b, " +
                            " follow_up_route c  " +
                            "WHERE " +
                            "b.chronic_disease_id = c.disease_type_id  " +
                            //" AND b.route_id =:routeId  " +
                            " and b.medical_team_id in(:teamIdList) ");
                }

                SQLQuery sqlQuery = ss.createSQLQuery(stringBuffer.toString());
                sqlQuery.setParameterList("teamIdList", teamIdList);
                sqlQuery.setResultTransformer(CriteriaSpecification.ALIAS_TO_ENTITY_MAP);
                List<Map> dbList = sqlQuery.list();
                List<Long> routeIdList = new ArrayList<>();
                if (CommonUtils.isNotEmpty(dbList)) {
                    for (Map map : dbList) {
                        Long routeId = Long.valueOf(String.valueOf(map.get("routeId")));
                        routeIdList.add(routeId);
                    }
                    setResult(routeIdList);
                } else {
                    setResult(null);
                }
            }
        };
        HibernateSessionTemplate.instance().execute(action);
        return action.getResult();
    }

    /**
     * 更新路径版本信息
     * @param followUpRoute
     */
    public void  updateFollowUpRouteVersion(final FollowUpRoute followUpRoute) {
        HibernateStatelessResultAction action = new AbstractHibernateStatelessResultAction() {
            @Override
            public void execute(StatelessSession ss) throws Exception {
                Query query = ss.createQuery("update FollowUpRoute p set p.versionNumber=:versionNumber,p.modifyId=:modifyId,p.modifyUsername=:modifyUsername,p.modifyDt=:modifyDt where p.routeId=:routeId");
                query.setParameter("versionNumber",followUpRoute.getVersionNumber());
                query.setParameter("modifyId",followUpRoute.getModifyId());
                query.setParameter("modifyUsername",followUpRoute.getModifyUsername());
                query.setParameter("modifyDt",followUpRoute.getModifyDt());
                query.setParameter("routeId",followUpRoute.getRouteId());
                query.executeUpdate();
            }
        };
        HibernateSessionTemplate.instance().execute(action);
    }

    public List<FollowUpRouteVO> queryRouteList(FollowUpRouteQo qo){
        QoHibernateStatelessResultAction<FollowUpRouteVO, FollowUpRouteQo> action = new QoHibernateStatelessResultAction<>(false, qo, FollowUpRouteVO.class);
        String sql = "SELECT route_id AS routeId,route_name AS routeName " +
                " FROM follow_up_route where 1=1 ";
        action.setSql(sql);
        action.addCondition(" AND organization_id=:organizationId ");
        action.addCondition(" AND follow_type = :followType ");
        action.addCondition(" AND route_name like :%keyword% ");

        HibernateSessionTemplate.instance().execute(action);
        return action.getResultList();
    }
}
